package com.suxin.http.request.intercept;

import com.suxin.http.model.RequestHttpEntity;
import com.suxin.http.request.HttpClientRequest;
import com.suxin.http.response.HttpClientResponse;

import java.io.IOException;
import java.net.URI;

/**
 * @author Tang
 * @classname InterceptHttpClientRequest
 * @description [ 拦截器增强 HttpClientRequest ]
 * @date 2023/3/3 16:41
 */
public class InterceptHttpClientRequest implements HttpClientRequest {

    private final HttpClientRequest httpClientRequest;

    private final Iterable<HttpClientRequestInterceptor> interceptors;

    public InterceptHttpClientRequest(HttpClientRequest httpClientRequest, Iterable<HttpClientRequestInterceptor> interceptors) {
        this.httpClientRequest = httpClientRequest;
        this.interceptors = interceptors;
    }

    @Override
    public HttpClientResponse execute(URI uri, String method, RequestHttpEntity requestHttpEntity) throws Exception {
        for (HttpClientRequestInterceptor interceptor : interceptors) {
            if (interceptor.isInterceptor(uri, method, requestHttpEntity)) {
                return interceptor.intercept();
            }
        }
        return httpClientRequest.execute(uri, method, requestHttpEntity);
    }

    @Override
    public void close() throws IOException {
        this.httpClientRequest.close();
    }
}
